package com.mazaiting.generator.utils;

import com.mazaiting.generator.enums.DbTypeEnum;
import com.mazaiting.generator.config.GenDataSource;
import lombok.extern.slf4j.Slf4j;
import oracle.jdbc.OracleConnection;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Objects;

/**
 * DB工具类
 */
@Slf4j
public class DbUtil {
    /**
     * 连接超时时间
     */
    private static final int CONNECTION_TIMEOUTS_SECONDS = 6;

    /**
     * 获得数据库连接
     */
    public static Connection getConnection(GenDataSource dataSource) throws ClassNotFoundException, SQLException {
        DriverManager.setLoginTimeout(CONNECTION_TIMEOUTS_SECONDS);
        Class.forName(dataSource.getDbTypeEnum().getDriverClass());
        // 获取连接
        Connection connection = DriverManager.getConnection(dataSource.getConnUrl(), dataSource.getUsername(), dataSource.getPassword());
        if (dataSource.getDbTypeEnum() == DbTypeEnum.Oracle) {
            ((OracleConnection) connection).setRemarksReporting(true);
        }

        return connection;
    }

    /**
     * 关闭数据库连接
     * @param conn 数据库连接
     */
    public static void close(Connection conn) {
        try {
            if (Objects.nonNull(conn) && !conn.isClosed()) {
                conn.close();
            }
        } catch (Exception e) {
            log.error("数据库连接关闭失败, 异常: {}", e.getMessage());
        }
    }

}